package cn.juque.jdfsystem.interceptor;

import cn.hutool.extra.spring.SpringUtil;
import cn.juque.common.constants.StringConstants;
import cn.juque.jdfsystem.cache.BlacklistInfoCache;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.Set;

/**
 * @author juque
 * @version 1.0.0
 * <ul>
 *     <li>BlacklistInterceptor</li>
 * </ul>
 * @date 2024-07-07
 **/
@Slf4j
public class BlacklistInterceptor implements HandlerInterceptor {

    private static final String UNKNOWN = "unknown";

    private static final Integer FIFTEEN = 15;

    private BlacklistInfoCache blacklistInfoCache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String ip = this.getClientIp(request);
        Set<String> set = this.getCache().get(null, false);
        boolean flag = set.contains(ip);
        if (flag) {
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
        }
        return !flag;
    }

    private BlacklistInfoCache getCache() {
        if (Objects.nonNull(this.blacklistInfoCache)) {
            return blacklistInfoCache;
        }
        synchronized (this) {
            if (Objects.nonNull(this.blacklistInfoCache)) {
                return this.blacklistInfoCache;
            }
            this.blacklistInfoCache = SpringUtil.getBean(BlacklistInfoCache.class);
            return this.blacklistInfoCache;
        }
    }

    /**
     * 从HttpServletRequest对象中获取客户端的真实IP地址
     *
     * @param request HttpServletRequest对象
     * @return 客户端的真实IP地址
     */
    private String getClientIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.isEmpty() || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.isEmpty() || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ip == null || ip.isEmpty() || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ip == null || ip.isEmpty() || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        // 对于通过多个代理的情况，第一个IP为客户端真实IP,若不存在则都为0:0:0:0:0:0:0:1
        if (ip != null && ip.length() > FIFTEEN) {
            int index = ip.indexOf(StringConstants.COMMA);
            if (index > 0) {
                ip = ip.substring(0, index);
            }
        }
        return ip;
    }
}
